package prototype.controller.dictionary;

import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import prototype.constant.EMessageConst;
import prototype.constant.UrlConst;
import prototype.constant.data.DictionaryConst;
import prototype.controller.AbstractController;
import prototype.data.Dictionary;
import prototype.exception.ObjectFieldException;

import javax.persistence.EntityManager;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpSession;

/**
 * Удаление записи из словаря
 */
@WebServlet("/" + UrlConst.URL_DICTIONARY_DELETE)
public class DictionaryDeleteController extends AbstractController {
	public static final String URL = UrlConst.URL_DICTIONARY_DELETE;

	@Override
	protected JsonObject execute(EntityManager entityManager, HttpSession session, JsonElement requestData) throws Exception {
		final JsonObject dictionaryJson = requestData.getAsJsonObject().get("dictionary").getAsJsonObject();
		Dictionary dictionary = new Dictionary(dictionaryJson);

		if (dictionary.getId() == null)
			throw new ObjectFieldException(EMessageConst.MISSING_OBJECT_ID, dictionary.getObjectType(), null, null, DictionaryConst.S_ID);

		entityManager.getTransaction().begin();
		Dictionary dictionary2 = entityManager.find(Dictionary.class, dictionary.getId());
		entityManager.remove(dictionary2);
		entityManager.getTransaction().commit();

		final JsonObject jsonObject = new JsonObject();
		return jsonObject;
	}
}
